//
//  ETAppealAlertViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/5/19.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class ETAppealAlertViewController: UIViewController {

    fileprivate var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    fileprivate lazy var panelView:WorkerSalaryPreView = {
        let view = WorkerSalaryPreView.init(frame: CGRect.zero)

        return view
    }()
    fileprivate lazy var secondPanelView:WorkerSalaryTPreView = {
        let view = WorkerSalaryTPreView.init(frame: CGRect.zero)
        
        return view
    }()
    
    private var okHandler: (()->Void)?
    private var message: [String: Any]?
    fileprivate var bodyTitle: String?
    fileprivate var realPaySalaryStr:String?
    fileprivate var protocolSalaryStr:String?
    fileprivate var reasonStr:String?
    //当前alert是否正在显示
    private var isShowing:Bool = false
    fileprivate var alertSort:Bool? = true
    init (_ message: [String: Any],dict:[String: Any], okHandler: @escaping ()-> Void){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = okHandler
        
        self.message = message
         realPaySalaryStr = message["RealPaySalary"] as? String
         protocolSalaryStr = message["ProtocolSalary"] as? String
        reasonStr = message["DeductionReason"] as? String
        self.bodyTitle = dict["body"] as? String
        
        if (realPaySalaryStr != nil){
            let realPaySalary = Double(realPaySalaryStr!)
            if (protocolSalaryStr != nil){
                let protocolSalary = Double(protocolSalaryStr!)
                if realPaySalary == protocolSalary{
                    self.alertSort = true
                }else{
                    self.alertSort = false
                }
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupUIView()
        self.updateViews()
        self.isShowing = true
        
    }
    
    
    fileprivate func setupUIView(){
        
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }

        if self.alertSort == false{
            self.panelView.companyLabel.text = self.bodyTitle
            self.panelView.realSalary.text = self.realPaySalaryStr! + "元"
            self.panelView.protocolSalary.text = self.protocolSalaryStr! + "元"
        self.panelView.reasonLabel.text = reasonStr
        self.panelView.companyLabel.sizeToFit()
        self.panelView.reasonLabel.sizeToFit()
        self.view.addSubview(self.panelView)
        let topH = self.panelView.companyLabel.frame.height + self.panelView.reasonLabel.frame.height + 375
        print(topH)
        self.panelView.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.centerY.equalTo(self.view)
            make.height.equalTo(topH)
        }
        self.panelView.agreeButton.addTarget(self, action: #selector(doRightButtonAction), for: .touchUpInside)
        self.panelView.appealButton.addTarget(self, action: #selector(doLeftButtonAction), for: .touchUpInside)
        }else{
            self.secondPanelView.companyName.text = self.bodyTitle
            self.secondPanelView.realSalary.text = self.realPaySalaryStr! + "元"
            self.secondPanelView.procotolSalary.text = self.protocolSalaryStr! + "元"
            self.secondPanelView.companyName.sizeToFit()
            self.view.addSubview(self.secondPanelView)
            let topH = self.secondPanelView.companyName.frame.height + 349
           self.secondPanelView.snp.makeConstraints { (make) in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.centerY.equalTo(self.view)
                make.height.equalTo(topH)
            }
         self.secondPanelView.agreeButton.addTarget(self, action: #selector(doRightButtonAction), for: .touchUpInside)
        self.secondPanelView.appealButton.addTarget(self, action: #selector(doLeftButtonAction2), for: .touchUpInside)
        }
    }
    
    deinit {
        self.isShowing = false
    }
    private func updateViews() {
        //self.messageLabel.text = self.message
    }
    @objc private func doLeftButtonAction() {
        
        let alert = UIAlertController(title: "确认申诉之后，请主动联系包工头，进行工资商议，以便在正式发", message: "", preferredStyle: .alert)
        let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
           // self.dismiss(animated: true, completion: nil)
            
        })
        let gotoAppstore = UIAlertAction(title: "确定申诉", style: .default, handler: { (action) in
            self.dismiss(animated: true, completion: nil)
            self.setWorkerSalaryAdvanceConsult(2)
        })
        alert.addAction(gotoAppstore)
        alert.addAction(refuseApp)
        self.present(alert, animated: true, completion: {
            
        })
    }
    @objc private func doLeftButtonAction2() {
        
        let alert = UIAlertController(title: "您的工资发放金额符合您的考勤统计，确认要申诉吗？恶意协商将影响您的个人信誉!", message: "", preferredStyle: .alert)
        let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
            // self.dismiss(animated: true, completion: nil)
            
        })
        let gotoAppstore = UIAlertAction(title: "坚持申诉", style: .default, handler: { (action) in
            self.dismiss(animated: true, completion: nil)
            self.setWorkerSalaryAdvanceConsult(2)
        })
        alert.addAction(gotoAppstore)
        alert.addAction(refuseApp)
        self.present(alert, animated: true, completion: {
            
        })
    }
    
    @objc private func doRightButtonAction() {
        self.setWorkerSalaryAdvanceConsult(1)
        if self.okHandler != nil {
            self.okHandler!()
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    fileprivate func setWorkerSalaryAdvanceConsult(_ sort:Int){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let advanceDetailID = self.message!["AdvanceDetailID"] as? String else {
            return
        }
    LCAPiSubManager.request(.SetWorkerSalaryAdvanceConsult(advanceDetailID: advanceDetailID, appealResult: sort, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    
                    return
                }
                WWSuccess("保存成功!")
            }
        }
    }
}
extension ETAppealAlertViewController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return AppealAlertViewControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return AppealAlertViewControllerTransitionDismiss()
    }
}

class AppealAlertViewControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! ETAppealAlertViewController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        if toVc.alertSort == true{
            let panelView = toVc.panelView
            let coverview = toVc.coverView
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
            panelView.alpha = 0.3
            panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
            UIView.animate(withDuration:0.1, animations: {
                coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
                panelView.transform = CGAffineTransform.identity
                panelView.alpha = 1
            }) { (finish) in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                toVc.view.addSubview(fromView!)
                toVc.view.sendSubview(toBack: fromView!)
            }
            
        }else{
            let panelView = toVc.secondPanelView
            let coverview = toVc.coverView
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
            panelView.alpha = 0.3
            panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
            UIView.animate(withDuration:0.1, animations: {
                coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
                panelView.transform = CGAffineTransform.identity
                panelView.alpha = 1
            }) { (finish) in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                toVc.view.addSubview(fromView!)
                toVc.view.sendSubview(toBack: fromView!)
            }
        }
    }
}

class AppealAlertViewControllerTransitionDismiss: NSObject,UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from) as! ETAppealAlertViewController
        
        //        let panelView = fromVc.panelView
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        }) { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
        
    }
}
